package com.skyolder.milkbee.web.rest.pub;

import java.time.ZonedDateTime;
import java.util.List;
import java.util.Optional;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.codahale.metrics.annotation.Timed;
import com.skyolder.milkbee.domain.Candidate;
import com.skyolder.milkbee.domain.Elector;
import com.skyolder.milkbee.domain.Leaguer;
import com.skyolder.milkbee.domain.Questionnaire;
import com.skyolder.milkbee.domain.User;
import com.skyolder.milkbee.dto.SimpleResult;
import com.skyolder.milkbee.dto.Ticket;
import com.skyolder.milkbee.dto.Vote;
import com.skyolder.milkbee.security.SecurityUtils;
import com.skyolder.milkbee.service.CandidateService;
import com.skyolder.milkbee.service.ElectorService;
import com.skyolder.milkbee.service.LeaguerService;
import com.skyolder.milkbee.service.QuestionnaireService;
import com.skyolder.milkbee.service.UserService;

/**
 * REST controller for managing Questionnaire.
 */
@RestController
@RequestMapping("/api/pub")
public class VoteResource {

    private final Logger log = LoggerFactory.getLogger(VoteResource.class);
        
    @Inject
    private QuestionnaireService questionnaireService;
    @Inject
    private CandidateService candidateService; 
    @Inject
    private ElectorService electorService;
    @Inject
    private UserService userService;
    @Inject
    private LeaguerService leaguerService;
    @GetMapping("/vote/{id}")
    @Timed
    public ResponseEntity<Vote> getVote(@PathVariable Long id) {
        log.debug("REST request to get Questionnaire : {}", id);
        Questionnaire questionnaire = questionnaireService.findOne(id);
        if(questionnaire==null){
        	new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        List<Candidate> candidates=candidateService.findByQuestionnaireId(questionnaire.getId());
        Vote v=new Vote();
        v.setId(questionnaire.getId());
        v.setCandidates(candidates);
        v.setGross(0L);
        for(Candidate c:candidates){
        	long x=c.getVote()==null?0:c.getVote();
        	v.setGross(v.getGross()+x);
        }
        v.setQuestionnaire(questionnaire);
        return  new ResponseEntity<>(v, HttpStatus.OK);
    }
    @PutMapping("/vote")
    @Timed
    public ResponseEntity<SimpleResult> getVote(@RequestBody Ticket ticket) {
    	log.info("ticket.getId():"+ticket.getId());
    	for(Long l:ticket.getCandidates()){
    		log.info("ticket.candidates:"+l);
    	}
    	Optional<User> ouser = userService.getUserWithAuthoritiesByLogin(SecurityUtils.getCurrentUserLogin());
    	User me=ouser.get();
    	List list=electorService.findByUserIdAndQuestionnaireId(me.getId(),ticket.getId());
    	if(list!=null&&list.size()>0){
    		log.info("list!=null&&list.size()>0");
    		return new ResponseEntity<>(new SimpleResult(false), HttpStatus.CONFLICT);
    	}
    	Questionnaire questionnaire =questionnaireService.findOne(ticket.getId());
    	if(questionnaire.getEndAt().isBefore(ZonedDateTime.now())){
    		log.info("questionnaire.getEndAt().isBefore(ZonedDateTime.now())");
    		return  new ResponseEntity<>(new SimpleResult(false), HttpStatus.BAD_REQUEST);
    	}
    	List cds=ticket.getCandidates();
    	if(cds==null){
    		log.info("cds==null");
    		return  new ResponseEntity<>(new SimpleResult(false), HttpStatus.BAD_REQUEST);
    	}
    	if(cds.size()>questionnaire.getSingle()){
    		log.info("cds.size()>questionnaire.getSingle()");
    		return  new ResponseEntity<>(new SimpleResult(false), HttpStatus.BAD_REQUEST);
    	}
    	List<Candidate> candidates=candidateService.findByQuestionnaireId(ticket.getId());
    	StringBuilder stringBuilder=new StringBuilder();
    	for(Long l:ticket.getCandidates()){
    		stringBuilder.append(l).append(",");
    		for(Candidate c:candidates){
    			if(c.getId()==l){
    				long x=c.getVote()==null?0:c.getVote();
    				c.setVote(x+1L);
    				candidateService.save(c);
    				break;
    			}
    		}
    	}
    	Leaguer leaguer=leaguerService.findByUser(me);
    	Elector elector=new Elector();
    	elector.setCreatedAt(ZonedDateTime.now());
    	elector.setLeaguerId(leaguer.getId());
    	elector.setQuestionnaireId(questionnaire.getId());
    	elector.setUserId(me.getId());
    	elector.setDetail(stringBuilder.toString());
    	electorService.save(elector);
    	SimpleResult sResult=new SimpleResult(true);
    	return  new ResponseEntity<>(sResult, HttpStatus.OK);
    }
    

}
